<template>
  <div class="members-container">
    <el-card shadow="hover">
      <template #header>
        <div class="card-header">
          <span>会员管理</span>
          <el-button type="primary" :icon="Plus" @click="handleCreate">
            新增会员
          </el-button>
        </div>
      </template>
      
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="姓名">
          <el-input
            v-model="searchForm.name"
            placeholder="请输入姓名"
            clearable
            style="width: 180px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input
            v-model="searchForm.phone"
            placeholder="请输入手机号"
            clearable
            style="width: 180px"
            @keyup.enter="handleSearch"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 180px">
            <el-option label="全部" :value="undefined" />
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">
            搜索
          </el-button>
          <el-button :icon="Refresh" @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 会员列表表格 -->
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="phone" label="手机号" width="130" />
        <el-table-column prop="email" label="邮箱" width="180" />
        <el-table-column prop="gender" label="性别" width="80">
          <template #default="{ row }">
            {{ row.gender === 1 ? '男' : row.gender === 2 ? '女' : '-' }}
          </template>
        </el-table-column>
        <el-table-column prop="birthday" label="生日" width="130">
          <template #default="{ row }">
            {{ formatDateYMD(row.birthday) }}
          </template>
        </el-table-column>
        <el-table-column prop="address" label="地址" min-width="150" show-overflow-tooltip />
        <el-table-column prop="level_name" label="等级" width="100" />
        <el-table-column prop="status" label="状态" width="80">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'danger'">
              {{ row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="handleEdit(row)"
            >
              编辑
            </el-button>
            <el-button
              link
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.page"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 会员编辑对话框 -->
    <MemberDialog
      v-model="dialogVisible"
      :member-id="currentMemberId"
      @success="handleDialogSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh } from '@element-plus/icons-vue'
import { getMemberList, deleteMember } from '@/api/members'
import MemberDialog from '@/components/MemberDialog.vue'
import { getMemberLevelList } from '@/api/memberLevels'

interface Member {
  id: string
  name: string
  phone: string
  email?: string
  gender?: number
  birthday?: string
  address?: string
  level_id?: string
  level_name?: string
  status?: number
  [key: string]: any
}

interface SearchForm {
  name: string
  phone: string
  status: number | undefined
}

interface Pagination {
  page: number
  pageSize: number
  total: number
}

const loading = ref(false)
const tableData = ref<Member[]>([])
const dialogVisible = ref(false)
const currentMemberId = ref<string | null>(null)

const searchForm = reactive<SearchForm>({
  name: '',
  phone: '',
  status: undefined
})

const pagination = reactive<Pagination>({
  page: 1,
  pageSize: 10,
  total: 0
})

// 会员等级映射：level_id -> level_name
const levelMap = ref<Record<string, string>>({})

// 加载会员等级并构建映射
const fetchLevelMap = async (): Promise<void> => {
  try {
    const res = await getMemberLevelList({})
    if (res.code === 200 && res.data) {
      const list = Array.isArray(res.data) ? res.data : (res.data.list || [])
      const map: Record<string, string> = {}
      list.forEach((item: any) => {
        if (item && item.id) {
          map[item.id] = item.name || '-'
        }
      })
      levelMap.value = map
    }
  } catch (e) {
    // 忽略等级加载错误，不阻塞页面
  }
}

// 格式化日期为 YYYY-MM-DD
const formatDateYMD = (value: string | number | Date | null | undefined): string => {
  if (!value) return '-'
  // 支持 'YYYY-MM-DD'、ISO 字符串或时间戳
  const date = typeof value === 'string' || typeof value === 'number' ? new Date(value) : value
  if (isNaN(date?.getTime?.())) return '-'
  const y = date.getFullYear()
  const m = String(date.getMonth() + 1).padStart(2, '0')
  const d = String(date.getDate()).padStart(2, '0')
  return `${y}-${m}-${d}`
}

// 获取会员列表
const fetchMemberList = async (): Promise<void> => {
  loading.value = true
  try {
    const params: Record<string, any> = {
      page: pagination.page,
      pageSize: pagination.pageSize,
      ...searchForm
    }
    // 移除空值
    Object.keys(params).forEach(key => {
      if (params[key] === '' || params[key] === undefined) {
        delete params[key]
      }
    })
    
    const res = await getMemberList(params)
    if (res.code === 200 && res.data) {
      const list = res.data.list || []
      // 补充等级名称
      tableData.value = list.map((item: any) => ({
        ...item,
        level_name: item.level_name || levelMap.value[item.level_id] || '-'
      }))
      pagination.total = res.data.total || 0
    }
  } catch (error) {
    console.error('获取会员列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = (): void => {
  pagination.page = 1
  fetchMemberList()
}

// 重置搜索
const handleReset = (): void => {
  searchForm.name = ''
  searchForm.phone = ''
  searchForm.status = undefined
  pagination.page = 1
  fetchMemberList()
}

// 新增会员
const handleCreate = (): void => {
  currentMemberId.value = null
  dialogVisible.value = true
}

// 编辑会员
const handleEdit = (row: Member): void => {
  currentMemberId.value = row.id
  dialogVisible.value = true
}

// 删除会员
const handleDelete = async (row: Member): Promise<void> => {
  try {
    await ElMessageBox.confirm(
      `确定要删除会员 "${row.name}" 吗？`,
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deleteMember({ id: row.id })
    ElMessage.success('删除成功')
    fetchMemberList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除会员失败:', error)
    }
  }
}

// 分页大小改变
const handleSizeChange = (size: number): void => {
  pagination.pageSize = size
  pagination.page = 1
  fetchMemberList()
}

// 页码改变
const handlePageChange = (page: number): void => {
  pagination.page = page
  fetchMemberList()
}

// 对话框操作成功
const handleDialogSuccess = (): void => {
  fetchMemberList()
}

onMounted(async (): Promise<void> => {
  await fetchLevelMap()
  fetchMemberList()
})
</script>

<style lang="scss" scoped>
.members-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-weight: 600;
    font-size: 16px;
  }
  
  .search-form {
    margin-bottom: 20px;
  }
  
  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>

